import React, { useEffect, useMemo, useState } from 'react'
import { TabRawState } from '../../types'
import axios from 'axios';
import { ListItem } from '../../components'
import { useNavigate } from 'react-router-dom';
const Classify: React.FC = () => {
  /********************** 数据请求 **********************************/
  // 1. 数据容器
  const [tabList, setTabList] = useState<TabRawState[]>([]);
  // 2. 请求方法 
  const fetchTabList = async () => {
    const resp = await axios.get('/api/tab');
    setTabList(resp.data.data)
  };
  // 3. 副作用函数
  useEffect(() => {
    fetchTabList()
  }, [])
  /********************** 高亮切换 **********************************/
  // 1. 容器
  const [tabIndex, setTabIndex] = useState<number>(0)
  // 2. 点击事件
  const handleClick = (i: number) => {
    // 高亮切换
    setTabIndex(i);
  }
  /********************** 内容切换数据 **********************************/
  const rightList = useMemo(() => {
    if(tabList.length === 0) return [] 
    return tabList[tabIndex].children
  }, [tabList, tabIndex])
  /********************** hooks **********************************/
  const navigate = useNavigate()
  return (
    <div className='tab'>
      <div className="left">
        <ul>
          {
            tabList.map((v, i) => {
              return <li key={i} onClick={() => handleClick(i)} className={i === tabIndex ? 'active' : ''}>{v.title}</li>
            })
          }
        </ul>
      </div>
      <div className="right">
          {
            rightList.map((v, i) => {
              return <ListItem onClick={() => navigate('/detail/' + v.id) } key={i} v={v} desc={
                <>
                  <div style={{fontSize: 12}}>{v.desc}</div>
                  <div style={{ color: 'red', fontSize: 14 }}>¥：{v.price}</div>
                </>
              }></ListItem>
            })
          }
      </div>
    </div>
  )
}


export default Classify